import { VideoState } from "../ws.ts";
import { nextTick } from "vue";

import type HistoryUserStore from "../../HistoryUserStore.ts";
import type { ReactiveData } from "../../model";
import type { ServerEventListener } from "../ws.ts";
import type { PlayerInst } from "@/pages/room/components/player/player.ts";

export function createRoomInitListener(
    data: ReactiveData,
    historyUserStore: HistoryUserStore,
    player: PlayerInst
): ServerEventListener<"room.init"> {
    return function (details) {
        player.disableListeners()

        historyUserStore.addAll(details.room.users);
        data.room = details.room;
        data.loading = false;

        nextTick(() => {
            player.enableListeners();
            const video = details.room.video;
            if (video?.url && video.state !== VideoState.STOP) {
                player.play(true).then(() => {
                    if (player.getSpeed() !== video.speed) {
                        player.speed(video.speed, true);
                    }
                    if (video.state === VideoState.PAUSE) {
                        player.pause(true);
                    }
                    player.seek(video.time / 1000, true);
                });
            }
        });
    }
}